package com.gxc.hash;

import java.util.Arrays;
import java.util.Scanner;
import java.util.Stack;

/**
 * 一贫如洗的樵夫阿里巴巴在去砍柴的路上，无意中发现了强盗集团的藏宝地，藏宝地有编号从0-N的箱子，每个箱子上面有一个数字，箱子排列成一个环，编号最大的箱子的下一个是编号为0的箱子。
 *
 * 请输出每个箱了贴的数字之后的第一个比它大的数，如果不存在则输出-1。
 *
 * 输入描述
 * 输入一个数字字串，数字之间使用逗号分隔，例如: 1,2,3,1
 *
 * 1 ≤ 字串中数字个数 ≤ 10000:
 * -100000 ≤ 每个数字值 ≤ 100000
 * 输出描述
 * 下一个大的数列表，以逗号分隔，例如: 2,3,6,-1,6
 *
 * 解法：
 * 1.暴力双指针
 * 2.单调递增栈
 */
public class SobberBox3 {

    public static void main2(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String strNumber = scanner.nextLine();

        StringBuilder builder = new StringBuilder();
        String[] split = strNumber.split(",");
        int low = 0;
        while (low<split.length) {
            int fast = low + 1;
            int lowN = Integer.parseInt(split[low]);
            while (low != fast) {
                if (fast == split.length) fast = 0;
                int fastN = Integer.parseInt(split[fast]);
                if (fastN > lowN) {
                    builder.append(fastN + ",");
                    break;
                }
                fast++;
            }
            if (fast == low) builder.append(-1 + ",");
            low++;
        }
        System.out.println(builder.substring(0, builder.length()-1));
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        // 读取整行输入并按逗号拆分
        String[] tmp = scanner.nextLine().split(",");
        int n = tmp.length;

        int[] res = new int[n];
        Arrays.fill(res, -1);
        int[] numArray = new int[n];
        for (int i = 0; i < n; i++) {
            numArray[i] = Integer.parseInt(tmp[i]);
        }
        Stack<Integer> stack = new Stack<>();

        for (int i = 0; i < n * 2 -1 ; i++) {
            int j = i%n;
            while (!stack.isEmpty() && numArray[j]>numArray[stack.peek()]) {
                res[stack.pop()] = numArray[j];
            }

            if (i<n) {
                stack.push(j);
            }
        }

        for (int i = 0; i < res.length; i++) {
            System.out.print(res[i]);
            if (i != n-1) System.out.print(",");
        }
    }
}
